跳到主要内容

141 环形链表

https://leetcode.cn/leetbook/read/top-interview-questions-easy/xnwzei/

https://leetcode.cn/problems/linked-list-cycle/description/

cost: 2m21s

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode* head) {
auto fast = head;
auto slow = head;
while (fast != nullptr) {
fast = fast->next;
slow = slow->next;
if (fast == nullptr) {
return false;
}
fast = fast->next;
if (fast == slow) {
return true;
}
}
return false;
}
};
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)